package com.lg.concurrent.atomic;

import java.util.concurrent.atomic.LongAccumulator;

public class LongAccumulatorTest {

    //这里使用LongAccumulator类
    public static LongAccumulator num = new LongAccumulator((a,b)->a+b, 0);
    

    //每次调用这个方法，都会对全局变量加一操作，执行10000次
    public void sum() {
        for (int i = 0; i < 10000; i++) {
            //LongAccumulator类的自增操作,这里的参数可以指定每次增加的数字
            num.accumulate(1);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LongAccumulatorTest demo = new LongAccumulatorTest();
        //下面就是新建两个线程,分别调用一次sum方法
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                demo.sum();
            }
        });

        Thread t2 =new Thread(new Runnable() {

            @Override
            public void run() {
                demo.sum();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("当前num的值为num= "+ num.get());

    }
}